package com.zyf.chapter02.behavior.iterator.snapshot.timestamp;

/**
 * 第二版本：增加一个时间戳，用来记录 删除/增加 的时间
 * 在遍历时拿当前时间和 删除/增加 时间进行比较
 * @author yifeng
 */
public class SnapshotArrayIterator<E> implements Iterator<E> {

    private long snapshotTimestamp;
    private int cursorInAll; // 在整个容器中的下标，而非快照中的下标
    private int leftCount; // 快照中还有几个元素未被遍历

    ArrayList<E> snapshotList;

    int cursor;

    public SnapshotArrayIterator(ArrayList<E> list) {
        this.snapshotTimestamp = System.currentTimeMillis();
        this.cursorInAll = 0;
        this.leftCount = list.getActualSize();
        snapshotList = list;
    }

    @Override
    public boolean hasNext() {
        return leftCount >= 0;
    }

    @Override
    public E next() {
        E currentItem = snapshotList.get(cursorInAll);
        justNext();
        return currentItem;
    }

    private void justNext() {
        while (cursorInAll < snapshotList.getTotalSize()) {
            long addTimestamp = snapshotList.getAddTimestamp(cursorInAll);
            long delTimestamp = snapshotList.getDelTimestamp(cursorInAll);
            // 比较时间
            if (snapshotTimestamp > addTimestamp && snapshotTimestamp < delTimestamp) {
                leftCount --;
                break;
            }
            cursorInAll++;
        }
    }

    @Override
    public E currentItem() {
        return snapshotList.get(cursor);
    }

    @Override
    public String toString() {
        return "SnapshotArrayIterator{" +
                "snapshotList=" + snapshotList +
                '}';
    }

    public static void main(String[] args) {
    }
}
